<?php
/**
 * User: 苏翔
 * Date: 2024/8/16 14:07
 */

namespace App\Dao;

use App\FundConf;
use App\Model\PriceDailyModel;
use App\Model\PriceHourlyModel;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;

class PriceDailyDao extends BaseDao
{

    #[Inject]
    protected PriceDailyModel $model;
    #[Inject]
    protected PriceHourlyModel $logModel;

    function getList($uid = 0, $category = 0, $min_id = 0, $max_id = 0, $size = 10): array
    {
        $size = max(1, (int)$size);
        $where = compact('uid', 'category');
        $where = array_filter($where);
        $orderDirection = 'desc';
        if ($min_id) {
            $where[] = ['id', '>', $min_id];
            $orderDirection = 'asc';
        } elseif ($max_id) {
            $where[] = ['id', '<', $max_id];
        }
        return $this->model->where($where)->orderBy('id', $orderDirection)->limit($size)->get()->toArray();
    }

    function lastLog(): array
    {
        // 读id最大一条，add_time<$add_time
        $rs = $this->logModel->orderBy('id', 'desc')->first();
        return $rs ? $rs->toArray() : [];
    }

    function getStats($start_time, $ceil_time)
    {
        // 得到log 开始结束时间 high low
        $rs = DB::table($this->logModel->getTable())
            ->whereBetween('key_time', [$start_time, $ceil_time])
            ->selectRaw('min(close) as lowest, max(close) as highest')
            ->get();
        $rs=$rs->toArray()[0];
        $rt=[];
        if($rs){
            $rt['lowest'] = $rs->lowest;
            $rt['highest'] = $rs->highest;
        }
        return $rt;
    }


    function exist($key)
    {
        return $this->model->where('key_date', $key)->value('id');
    }

    function handle($time_key)
    {
        $lastLog = $this->lastLog();

        $close = $lastLog['close'] ?? 0;
        if (!($close > 0)) {
            echo "lastLog empty close \n";
            return false;
        }
        if (!$this->exist($time_key)) {
            return $this->add($time_key, $lastLog);
        }
        $data = $this->getStats($time_key, "$time_key 23:59:59");
        echo "handle $time_key \n";
        print_r($data);
        if (!$data) {
            return false;
        }
        $data['close'] = $close;
        return $this->model->where('key_date', $time_key)->update($data);
    }

    function add($time_key, $log)
    {

        $open = $log['open'] ?? 0;
        $close = $log['close'] ?? 0;
        if (!$open) {
            $open = $close;
        }

        if (!($close > 0)) {
            return false;
        }

        $data = [
            'key_date' => $time_key,
            'close' => $close,
            'open' => $open,
            'highest' => $close,
            'lowest' => $open,
            'add_time' => time(),
        ];

        return $this->model->insertGetId($data);
    }

}
